const express = require('express');
const router = express.Router();
const Hotel = require('../models/Hotel');

// 获取所有酒店
router.get('/', async (req, res) => {
  try {
    const { 
      city, 
      starRating, 
      minPrice, 
      maxPrice, 
      isPopular, 
      page = 1, 
      limit = 10,
      sortBy = 'rating',
      sortOrder = 'desc',
      search
    } = req.query;

    // 构建查询条件
    const query = { isAvailable: true };
    
    if (city) query.city = new RegExp(city, 'i');
    if (starRating) query.starRating = Number(starRating);
    if (minPrice || maxPrice) {
      query.price = {};
      if (minPrice) query.price.$gte = Number(minPrice);
      if (maxPrice) query.price.$lte = Number(maxPrice);
    }
    if (isPopular !== undefined) query.isPopular = isPopular === 'true';
    if (search) {
      query.$or = [
        { name: new RegExp(search, 'i') },
        { description: new RegExp(search, 'i') },
        { city: new RegExp(search, 'i') },
        { tags: { $in: [new RegExp(search, 'i')] } }
      ];
    }

    // 构建排序
    const sort = {};
    sort[sortBy] = sortOrder === 'desc' ? -1 : 1;

    // 分页参数
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    // 执行查询
    const hotels = await Hotel.find(query)
      .sort(sort)
      .skip(skip)
      .limit(limitNum);

    // 获取总数
    const total = await Hotel.countDocuments(query);

    res.json({
      success: true,
      data: hotels,
      pagination: {
        page: pageNum,
        limit: limitNum,
        total,
        pages: Math.ceil(total / limitNum)
      }
    });
  } catch (error) {
    console.error('获取酒店列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取酒店列表失败',
      error: error.message
    });
  }
});

// 按城市获取酒店
router.get('/city/:city', async (req, res) => {
  try {
    const { city } = req.params;
    const { limit = 10, sortBy = 'rating', sortOrder = 'desc' } = req.query;

    const sort = {};
    sort[sortBy] = sortOrder === 'desc' ? -1 : 1;

    const hotels = await Hotel.find({ 
      city: new RegExp(city, 'i'), 
      isAvailable: true 
    })
      .sort(sort)
      .limit(parseInt(limit));

    const total = await Hotel.countDocuments({ 
      city: new RegExp(city, 'i'), 
      isAvailable: true 
    });

    res.json({
      success: true,
      data: hotels,
      total
    });
  } catch (error) {
    console.error('按城市获取酒店失败:', error);
    res.status(500).json({
      success: false,
      message: '按城市获取酒店失败',
      error: error.message
    });
  }
});

// 获取热门酒店
router.get('/popular', async (req, res) => {
  try {
    const { limit = 6 } = req.query;

    const hotels = await Hotel.find({ 
      isPopular: true, 
      isAvailable: true 
    })
      .sort({ rating: -1, bookingCount: -1 })
      .limit(parseInt(limit));

    res.json({
      success: true,
      data: hotels
    });
  } catch (error) {
    console.error('获取热门酒店失败:', error);
    res.status(500).json({
      success: false,
      message: '获取热门酒店失败',
      error: error.message
    });
  }
});

// 获取单个酒店详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const hotel = await Hotel.findById(id);
    
    if (!hotel) {
      return res.status(404).json({
        success: false,
        message: '酒店不存在'
      });
    }

    res.json({
      success: true,
      data: hotel
    });
  } catch (error) {
    console.error('获取酒店详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取酒店详情失败',
      error: error.message
    });
  }
});

// 获取酒店统计信息
router.get('/stats/overview', async (req, res) => {
  try {
    const stats = await Hotel.aggregate([
      {
        $group: {
          _id: '$city',
          count: { $sum: 1 },
          avgPrice: { $avg: '$price' },
          avgRating: { $avg: '$rating' }
        }
      },
      {
        $sort: { count: -1 }
      }
    ]);

    const totalHotels = await Hotel.countDocuments({ isAvailable: true });
    const popularHotels = await Hotel.countDocuments({ 
      isPopular: true, 
      isAvailable: true 
    });

    res.json({
      success: true,
      data: {
        totalHotels,
        popularHotels,
        citiesStats: stats
      }
    });
  } catch (error) {
    console.error('获取酒店统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取酒店统计失败',
      error: error.message
    });
  }
});

// 搜索酒店
router.get('/search/:keyword', async (req, res) => {
  try {
    const { keyword } = req.params;
    const { limit = 10, page = 1 } = req.query;

    const query = {
      isAvailable: true,
      $or: [
        { name: new RegExp(keyword, 'i') },
        { description: new RegExp(keyword, 'i') },
        { city: new RegExp(keyword, 'i') },
        { address: new RegExp(keyword, 'i') },
        { tags: { $in: [new RegExp(keyword, 'i')] } },
        { amenities: { $in: [new RegExp(keyword, 'i')] } }
      ]
    };

    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    const hotels = await Hotel.find(query)
      .sort({ rating: -1, bookingCount: -1 })
      .skip(skip)
      .limit(limitNum);

    const total = await Hotel.countDocuments(query);

    res.json({
      success: true,
      data: hotels,
      pagination: {
        page: pageNum,
        limit: limitNum,
        total,
        pages: Math.ceil(total / limitNum)
      }
    });
  } catch (error) {
    console.error('搜索酒店失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索酒店失败',
      error: error.message
    });
  }
});

module.exports = router; 